package com.atguigu.tingshu.order.context;

import com.atguigu.tingshu.order.interceptor.OrderHandlerInterceptor;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class OrderHandlerInterceptorContext implements ApplicationContextAware {
    //责任链任务实现类存储容器
    private static final List<OrderHandlerInterceptor> orderHandlerInterceptors = new ArrayList<>();

    //责任链调用方法入口
    public static OrderInfoVo entry(OrderInfoVo orderInfoVo){
        for (OrderHandlerInterceptor orderHandlerInterceptor : orderHandlerInterceptors) {
            orderInfoVo = orderHandlerInterceptor.sbumitOrderRequestProcess(orderInfoVo);
        }
        return orderInfoVo;
    }

    //责任链任务执行进入容器及排序
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, OrderHandlerInterceptor> beans = applicationContext.getBeansOfType(OrderHandlerInterceptor.class);
        beans.values().stream().sorted((o1, o2) -> o1.sort()-o2.sort()).forEach(orderHandlerInterceptors::add);
    }
}
